<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: isCollapsed }">
      <!-- 用户资料 -->
      <div class="user-profile">
        <div class="avatar" @click="showAvatarDialog">
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar-img" />
          <span v-else class="iconfont-user">{{ userInitial }}</span>
        </div>
        <div class="user-info" v-if="!isCollapsed">
          <div class="name">{{ userName }}</div>
          <div class="position">{{ userPosition }}</div>
        </div>
      </div>

      <!-- 主菜单 - 使用admin的数据 -->
      <nav class="menu">
        <div v-for="(item, index) in navList" :key="index" class="menu-item" :class="{ active: isMenuActive(item.url) }"
          @click="navigateTo(item.url)">
          <span class="iconfont" :class="item.icon"></span>
          <span class="text" v-if="!isCollapsed">{{ item.name }}</span>
        </div>
      </nav>

      <!-- 底部菜单 -->
      <div class="footer-menu">
          <div class="menu-item vip-expiry">
            <div class="vip-expiry-badge">
              <i class="iconfont icon-rocket"></i>
              <span v-if="!isCollapsed">VIP到期: {{ vipExpiryDate }}</span>
            </div>
          </div>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部导航栏 - 使用workspace样式 -->
      <header class="top-header">
        <div class="header-left">
          <button class="toggle-btn" @click="toggleSidebar">
            <span class="iconfont" :class="isCollapsed ? 'icon-expand' : 'icon-collapse'"></span>
          </button>
          <div class="breadcrumb">
            {{ activeMenuName }}
          </div>
        </div>
        <div class="header-right">
          <div class="header-button contact-button" @click="navigateToContact">
            <i class="iconfont icon-help"></i>
            <span>联系我们</span>
          </div>
          <div class="header-button logout-button" @click="handleLogout">
            <i class="iconfont icon-logout"></i>
            <span>退出登录</span>
          </div>
        </div>
      </header>

      <!-- 页面内容 -->
      <div class="content">
        <router-view></router-view>
      </div>
    </main>

    <!-- 头像修改对话框 -->
    <div class="avatar-dialog" v-if="avatarDialogVisible">
      <div class="dialog-mask" @click="hideAvatarDialog"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>修改头像</h3>
          <button class="close-btn" @click="hideAvatarDialog">
            <span class="iconfont icon-close"></span>
          </button>
        </div>
        <div class="dialog-body">
          <div class="avatar-preview">
            <img v-if="previewAvatar" :src="previewAvatar" class="preview-img" />
            <div v-else class="avatar-placeholder">
              <span class="iconfont icon-user"></span>
            </div>
          </div>
          <div class="upload-controls">
            <input type="file" id="avatar-upload" ref="fileInput" accept="image/*" @change="handleFileChange"
              style="display: none" />
            <button class="upload-btn" @click="triggerFileInput">
              <span class="iconfont icon-upload"></span>
              选择图片
            </button>
            <button class="confirm-btn" :disabled="!selectedFile" @click="uploadAvatar">
              确认上传
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from 'vue-router';
import { useRouterStore, useIndexStore } from "@/store/path";
import { vToast } from "@/plugins/vToast";
import { vConfirm } from "@/plugins/vConfirm";
import { get, post, upload } from '@/request';
import { useUserInfoStore } from '@/store/userInfoStore';

const router = useRouter();
const route = useRoute();
const routerStore = useRouterStore();
const indexStore = useIndexStore();

// 状态管理
const isCollapsed = ref(false);

// 头像相关状态
const avatarUrl = ref(localStorage.getItem('avatarUrl') || '');
const avatarDialogVisible = ref(false);
const selectedFile = ref(null);
const previewAvatar = ref('');
const fileInput = ref(null);

// 用户信息
const userInfo = computed(() => {
  return JSON.parse(localStorage.getItem("userInfo") || "{}");
});

// 计算是否为子账号
const isSubAccount = computed(() => {
  // 同时检查is_sub_account和is_sub字段，处理可能的不同类型值
  const subAccountStatus = userInfo.value.is_sub_account;
  const subStatus = userInfo.value.is_sub;
  const permission = userInfo.value.permission || '';
  
  // 情况1：明确is_sub为字符串'0'或数字0时，不是子账号
  if (subStatus === '0' || subStatus === 0) {
    return false;
  }
  
  // 情况2：检查permission字段，如果是admin或superadmin，则不是子账号
  if (['admin', 'superadmin'].includes(permission)) {
    return false;
  }
  
  // 其他情况都视为子账号
  return true;
});

// VIP到期时间
const vipExpiryDate = computed(() => {
  // 从用户信息中获取VIP到期时间，如果不存在则使用默认时间
  const expiryDate = userInfo.value.vipExpiry || '2024-12-31';
  return expiryDate;
});

// 获取用户首字母
const userInitial = computed(() => {
  const username = userInfo.value.username || '管理员';
  return username.charAt(0);
});

// 获取用户名
const userName = computed(() => {
  return userInfo.value.username || '管理员';
});

// 获取用户职位
const userPosition = computed(() => {
  const permission = userInfo.value.permission || '';
  if (['superadmin', 'admin'].includes(permission)) {
    return '管理员操作台';
  }
  return '员工操作台';
});

// 从admin的asideNav.vue中获取菜单数据
const fullNavList = [
  { name: "首页", icon: "icon-home", url: "/admin/index" },
  { name: "档期管理", icon: "icon-date", url: "/admin/calendar" },
  { name: "职位分类管理", icon: "icon-date", url: "/admin/category" },
  { name: "职位管理", icon: "icon-user", url: "/admin/position/list" },
  { name: "素材管理", icon: "icon-instagram", url: "/admin/material/list" },
  { name: "订单管理", icon: "icon-order", url: "/admin/order/list" },
  { name: "营业额统计", icon: "icon-money", url: "/admin/money" },
  { name: "员工管理", icon: "icon-user", url: "/admin/staff" },
  {    
    // 员工 
    id: "dashboard",
    name: "工作台",
    icon: "icon-dashboard",
    url: "/workspace/main",
  },
  {
    // 员工 
    id: "orders",
    name: "订单状态",
    icon: "icon-order",
    url: "/workspace/orders",
  },
  {
    // 员工 
    id: "messages",
    name: "消息中心",
    icon: "icon-message",
    url: "/workspace/messages",
  },
  {    // 员工 
    id: "finance",
    name: "财务管理",
    icon: "icon-money",
    url: "/workspace/finance",
  },
  {
    name: "任务日历", icon: "icon-calendar", url: "/workspace/calendar"
  },
  {

    name: "员工任务明细", icon: "icon-calendar", url: "/workspace/task"
  },
  { name: "系统设置", icon: "icon-setting", url: "/admin/settings", requireAdmin: true }
];

// 子账号可见的菜单
const subAccountNavList = [
  {
    id: "dashboard",
    name: "工作台",
    icon: "icon-dashboard",
    url: "/workspace/main",
  },
  {
    id: "orders",
    name: "订单状态",
    icon: "icon-order",
    url: "/workspace/orders",
  },
  {
    id: "messages",
    name: "消息中心",
    icon: "icon-message",
    url: "/workspace/messages",
  },
  {
    id: "finance",
    name: "财务管理",
    icon: "icon-money",
    url: "/workspace/finance",
  }
];

// 根据用户类型决定显示的菜单
const navList = computed(() => {
  const permission = userInfo.value.permission || '';
  
  // 子账号且不是管理员的，显示4个菜单
  if (isSubAccount.value && !['admin', 'superadmin'].includes(permission)) {
    return subAccountNavList;
  }
  
  // 其他用户（包括管理员子账号），显示全部菜单但排除那4个子账号菜单
  const excludedUrls = subAccountNavList.map(item => item.url);
  return fullNavList.filter(item => !excludedUrls.includes(item.url));
});

// 计算当前激活的菜单名称
const activeMenuName = computed(() => {
  const currentPath = route.path;
  const activeItem = navList.value.find(item => currentPath.includes(item.url));
  return activeItem ? activeItem.name : '首页';
});

// 检查菜单是否激活
function isMenuActive(url) {
  return route.path.includes(url);
}

// 导航到指定URL
function navigateTo(url) {
  router.push(url);
}

// 切换侧边栏
function toggleSidebar() {
  isCollapsed.value = !isCollapsed.value;
}

// 显示头像对话框
function showAvatarDialog() {
  avatarDialogVisible.value = true;
}

// 隐藏头像对话框
function hideAvatarDialog() {
  avatarDialogVisible.value = false;
  // 重置上传状态
  selectedFile.value = null;
  previewAvatar.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
}

// 触发文件选择
function triggerFileInput() {
  fileInput.value?.click();
}

// 获取用户信息
const getuserInfo = async () => {
  try {
    const res = await get("/user/info");
    if (res && res.code === 200) {
      // 更新用户信息到localStorage
      const userInfoToStore = {
        username: res.data.username,
        real_name: res.data.real_name,
        company: res.data.company_name || res.data.company,
        phone: res.data.mobile || res.data.phone,
        permission: res.data.permission,
        avatar: res.data.avatar,
        is_sub: res.data.is_sub !== undefined ? String(res.data.is_sub) : '0',
        sub_mobile: res.data.sub_mobile || ''
      };
      localStorage.setItem("userInfo", JSON.stringify(userInfoToStore));
      
      // 更新头像URL
      if (res.data.avatar) {
        localStorage.setItem('avatarUrl', res.data.avatar);
        avatarUrl.value = res.data.avatar;
      }
    } else {
      vToast({ message: res?.msg || "获取用户信息失败" });
      if (res?.code === 401) {
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        router.push('/user/login');
      }
    }
  } catch (error) {
    vToast({ message: "获取用户信息失败" });
    console.error("获取用户信息失败:", error);
  }
};

// 处理文件选择
function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      vToast({ message: '请选择图片文件' });
      return;
    }
    
    // 检查文件大小（限制为2MB）
    if (file.size > 2 * 1024 * 1024) {
      vToast({ message: '图片文件大小不能超过2MB' });
      return;
    }
    
    selectedFile.value = file;
    // 创建预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      previewAvatar.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
}

// 上传头像
async function uploadAvatar() {
  if (!selectedFile.value) {
    vToast({ message: '请选择要上传的图片' });
    return;
  }

  try {
    // 显示上传中状态
    vToast({ message: '头像上传中...', duration: 0 });
    
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const res = await upload('/user/uploadAvatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    // 清除上传中提示
    if (res && res.code === 200) {
      vToast({ message: '头像上传成功' });
      
      // 使用Pinia store更新头像信息
      const userInfoStore = useUserInfoStore();
      if (res.data.avatar_url) {
        userInfoStore.updateAvatar(res.data.avatar_url);
        localStorage.setItem('avatarUrl', res.data.avatar_url);
        avatarUrl.value = res.data.avatar_url;
      }
      
      // 重新从服务器获取完整用户信息
      getuserInfo();
      hideAvatarDialog();
    } else {
      vToast({ message: res?.msg || '头像上传失败' });
    }
  } catch (error) {
    console.error('上传头像失败:', error);
    vToast({ message: '头像上传失败' });
  }
}

// 联系我们
function navigateToContact() {
  vToast('联系我们功能开发中');
}

// 退出登录
function handleLogout() {
  vConfirm({
    message: '确定要退出登录吗？',
    confirmText: '确定',
    cancelText: '取消'
  }).then(() => {
    // 清除用户信息和token
    localStorage.removeItem('userInfo');
    localStorage.removeItem('avatarUrl');
    localStorage.removeItem('token');
    // 跳转到登录页
    router.push('/user/login');
  }).catch(() => {
    // 取消退出登录，不做任何处理
  });
}

// 初始化
onMounted(async () => {
  // 检查是否已登录
  const storedUserInfo = localStorage.getItem('userInfo');
  if (!storedUserInfo) {
    router.push('/login');
    return;
  }
  
  // 调用getuserInfo方法获取最新的用户信息
  await getuserInfo();
  
  // 解析用户信息
  const parsedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  
  // 对于子账号，如果当前路径是默认首页或未指定，重定向到工作台
  // 使用与isSubAccount计算属性相同的判断逻辑
  const subAccountStatus = parsedUserInfo.is_sub_account;
  const subStatus = parsedUserInfo.is_sub;
  const permission = parsedUserInfo.permission || '';
  
  if (((subAccountStatus === true || subAccountStatus === '1' || subAccountStatus === 1) || 
       (subStatus !== '0' && subStatus !== 0 && !['admin', 'superadmin'].includes(permission))) && 
      (route.path === '/' || route.path === '/admin/index')) {
    router.push('/workspace/main');
  }
});
</script>

<style scoped lang="less">
.admin-layout {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

/* 侧边栏 - 恢复原来的样式 */
.sidebar {
  width: 240px;
  background-color: #f1f2f6;
  color: #323335;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.sidebar.collapsed {
  width: 80px;
}

/* 用户资料 - 恢复原来的样式 */
.user-profile {
  padding: 40px 20px;
  display: flex;
  align-items: center;
}

.avatar {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background-color: var(--bs-theme-color);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  transition: all 0.3s;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  }
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.iconfont-user {
  font-size: 24px;
}

.user-info {
  margin-left: 12px;
}

.name {
  font-weight: 600;
  font-size: 20px;
}

.position {
  font-size: 16px;
  color: #7a7d81;
}

/* 菜单 */
.menu {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 6px;
  text-decoration: none;
  color: inherit;
}

.menu-item:hover {
  color: var(--bs-theme-color);
}

.menu-item.active {
  background-color: #fff;
  color: var(--bs-theme-color);
}

.menu-item .iconfont {
  font-size: 20px;
  width: 24px;
  text-align: center;
}

.menu-item .text {
  margin-left: 12px;
  white-space: nowrap;
}

/* 底部菜单 */
.footer-menu {
  border-top: 1px solid #e4e5e9;
  padding: 10px 0;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  min-width: 0;
  overflow-y: auto;
}

/* 顶部导航栏 */
.top-header {
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  margin-right: 20px;
  color: #323335;
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: #ddd 1px solid;
}

.toggle-btn:hover {
  background-color: #f1f2f6;
}

/* 顶栏文字增大到与边栏一致（20px） */
.breadcrumb {
  font-size: 15px;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  /* 移除gap，因为现在使用左侧边框分隔按钮 */
  font-size: 15px;
}

.header-item {
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.header-item:hover {
  background-color: #f1f2f6;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 20px;
}

/* 头像对话框 */
.avatar-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-content {
  position: relative;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background-color: #f1f2f6;
  color: #333;
}

.avatar-preview {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.preview-img {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-color: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  color: #6c757d;
}

.upload-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-bottom: 20px;
}

.upload-btn,
.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.upload-btn {
  background-color: #6c757d;
  color: white;
}

.upload-btn:hover {
  background-color: #5a6268;
}

.confirm-btn {
  background-color: #007bff;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.vip-expiry-badge {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    color: #ffd700;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    min-width: 100px;
    font-weight: 500;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    transition: all 0.3s ease;
  }
  
  .vip-expiry-badge:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4);
  }
  
  .vip-expiry-badge i.iconfont {
    font-size: 14px;
    color: #ffd700;
  }

/* 简约集成式顶栏按钮 - 保留已修改的样式 */
.header-button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 20px;
  height: 60px;
  border: none;
  border-left: 1px solid #e8e8e8;
  background-color: transparent;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: none;
  margin-left: 0;
  position: relative;
}

.header-button:hover {
  background-color: #f5f5f5;
  color: #333;
  border-color: #e8e8e8;
  transform: none;
  box-shadow: none;
}

.header-button:active {
  background-color: #e6f7ff;
  color: var(--bs-theme-color);
  border-color: #e8e8e8;
}

/* 联系我们按钮 - 信息蓝色调 */
.contact-button {
  color: var(--bs-theme-color);
  border-left: 1px solid #e8e8e8;
}

.contact-button:hover {
  background-color: #f5f5f5;
  color: var(--bs-theme-color);
}

/* 退出登录按钮 - 中性灰色调 */
.logout-button {
  color: #666;
  border-left: 1px solid #e8e8e8;
}

.logout-button:hover {
  background-color: #f5f5f5;
  color: #ff4d4f;
}

.header-button i.iconfont {
  font-size: 14px;
  transition: none;
}

.header-button:hover i.iconfont {
  transform: none;
}
</style>